import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Button, Descriptions, Modal } from 'antd';
import PropTypes from 'prop-types';
import { routerRedux } from 'dva/router';
import PreviewModal from '@/components/PreviewModal';
import { publishStatus, channelCdList } from '../messageTemplateManagement/variable';
import MaskText from '@/components/MaskText';

const current = 1;
const pageSize = 10;
const mapStateToProps = (state: any) => ({
  messageManagement: state.messageManagement,
  loading: state.loading.effects['messageManagement/getFetchPage'],
});
// const channelCdList = [
//   { label: '邮件', value: 1 },
//   { label: 'JPush', value: 2 },
//   { label: 'KAFKA', value: 3 },
//   { label: 'MQTT', value: 4 },
//   { label: '短信', value: 5 },
//   { label: '第三方', value: 9 },
//   { label: '站内信', value: 99 },
// ];
class MessageManagementDetail extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      detail: {},
      info: {},
      visible: false,
      contentData: undefined,
      type: undefined,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const record = sessionStorage.getItem('messagePushId') || '{}';
    const { pushId, msgCd, projectId, approvalStatus } = JSON.parse(record);
    // console.log(msgCd, projectId, approvalStatus);

    if (pushId) {
      dispatch({
        type: 'messageManagement/getFetchPage',
        payload: { url: '/message/record/findByPage', pushId, current: 1, pageSize: 10 },
        callback: (response: any) => {
          this.setState({
            detail: response.data.list[0],
          });
        },
      });
    }

    if (msgCd && projectId) {
      dispatch({
        type: 'messageManagement/getDataWithRes',
        payload: { url: '/message/template/findTemplateDetail', msgCd, projectId },
        callback: res => {
          const { statusCode, data } = res;
          if (statusCode === '0') {
            this.setState({
              info: data,
            });
          }
        },
      });
    }
  }
  get timeCom() {
    const { pushPeriod, timer, interval } = this.state?.info;
    return pushPeriod == 1
      ? '实时'
      : pushPeriod == 2
      ? `定时：${timer}`
      : pushPeriod == 3
      ? `间隔：${interval}小时`
      : '';
  }

  get publishStatus() {
    const { releaseFlag } = this.state?.info;
    return publishStatus.find(e => e.value == releaseFlag)?.label;
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'messageManagement/initData',
    });
  }

  goback = () => {
    const {
      messageManagement: {
        pageData: { pagination },
      },
      dispatch,
    } = this.props;
    const { formValues } = this.state;
    dispatch(
      routerRedux.push({
        pathname: '/messageCenter/messageManagement',
        state: { ...formValues, page: pagination.current - 1, size: pagination.pageSize },
      }),
    );
  };

  getStatus = (text: any, data: any) => {
    let list = data.filter(d => d.value === text);
    if (list.length > 0) {
      return list[0].label;
    } else {
      return text;
    }
  };

  handlePreview = (msgContent: any, type: any) => {
    this.setState({ visible: true, contentData: msgContent, type });
  };

  getFailureData = (remark: any) => {
    let txt = '';
    if (remark) {
      remark = '[' + remark + ']';
      try {
        const result = JSON.parse(remark);
        const latestMsg = result[result.length - 1];
        if (typeof latestMsg === 'object') {
          txt = JSON.stringify(latestMsg);
        }
      } catch (e) {}
    }
    return txt;
  };

  render() {
    const { visible, detail, contentData, type, info } = this.state;
    const msgStatus = [
      '发送失败',
      '待推送',
      '发送中',
      '待重发',
      '未送达',
      '发送成功',
      '已读',
      '已取消',
    ];
    const stateTxt = (detail && msgStatus[detail.msgStatus]) || '';

    return (
      <div>
        <Card bordered={false}>
          <Descriptions
            title={<span style={{ fontWeight: 'bold' }}>消息发送</span>}
            column={2}
            style={{ marginLeft: 10, marginRight: 10, marginTop: 10 }}
          >
            <Descriptions.Item label="消息编号">
              {detail && detail.pushId ? detail.pushId : ''}
            </Descriptions.Item>
            <Descriptions.Item label="发送方式">
              {detail?.manualFlag === 1 ? '手动' : '自动'}
            </Descriptions.Item>
            <Descriptions.Item label="发送状态">{stateTxt}</Descriptions.Item>
            <Descriptions.Item label="发送状态更新时间">
              {detail && detail.updateDate ? detail.updateDate : ''}
            </Descriptions.Item>
            {detail.msgStatus == 0 || detail.msgStatus == 4 ? (
              <>
                <Descriptions.Item label={stateTxt + '原因'}>
                  {this.getFailureData(detail.remark)}
                </Descriptions.Item>
              </>
            ) : null}
          </Descriptions>
        </Card>
        <Card bordered={false}>
          <Descriptions
            title={<span style={{ fontWeight: 'bold' }}>消息接收</span>}
            column={2}
            style={{ marginLeft: 10, marginRight: 10, marginTop: 10 }}
          >
            <Descriptions.Item label="受众对象组编号">
              {detail && detail.audienceGroupId ? detail.audienceGroupId : ''}
            </Descriptions.Item>
            <Descriptions.Item label="受众对象组名称">
              {detail && detail.audienceGroupName ? detail.audienceGroupName : ''}
            </Descriptions.Item>
            <Descriptions.Item label="受众对象">
              {detail && detail.receiverId && <MaskText text={detail.receiverId} type="audience" />}
            </Descriptions.Item>
          </Descriptions>
        </Card>
        <Card bordered={false}>
          <Descriptions
            title={<span style={{ fontWeight: 'bold' }}>消息模板</span>}
            column={2}
            style={{ marginLeft: 10, marginRight: 10, marginTop: 10 }}
          >
            <Descriptions.Item label="模板编号">
              {detail && detail.msgCd ? detail.msgCd : ''}
            </Descriptions.Item>
            <Descriptions.Item label="模板名称">
              {detail && detail.msgTitle ? detail.msgTitle : ''}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions column={1} style={{ marginLeft: 10, marginRight: 10 }}>
            <Descriptions.Item label="发布状态">{this.publishStatus}</Descriptions.Item>
            <Descriptions.Item label="模板内容">
              {/* {detail && detail.msgContent ? detail.msgContent : ''} */}
              {info?.tplType === 3 ? (
                <Button
                  disabled={!detail.msgContent}
                  onClick={() => this.handlePreview(detail.msgContent, 'onlyVertical')}
                  size={'small'}
                  style={{ marginLeft: 75 }}
                >
                  预览
                </Button>
              ) : (
                <div style={{ whiteSpace: 'normal' }}>{detail?.msgContent}</div>
              )}
            </Descriptions.Item>
          </Descriptions>
        </Card>
        <Card bordered={false}>
          <Descriptions
            title={<span style={{ fontWeight: 'bold' }}>消息渠道</span>}
            column={2}
            style={{ marginLeft: 10, marginRight: 10, marginTop: 10 }}
          >
            <Descriptions.Item label="渠道类型">
              {channelCdList.find(e => e.value === detail?.channelCd)?.label}
            </Descriptions.Item>
            {detail?.channelCd != 99 && (
              <Descriptions.Item label="渠道发送方">
                {detail && detail.senderId ? detail.senderId : ''}
              </Descriptions.Item>
            )}
          </Descriptions>
        </Card>
        <Card bordered={false}>
          <Descriptions
            title={<span style={{ fontWeight: 'bold' }}>消息属性</span>}
            column={2}
            style={{ marginLeft: 10, marginRight: 10, marginTop: 10 }}
          >
            <Descriptions.Item label="推送方式">{this.timeCom}</Descriptions.Item>
            <Descriptions.Item label="推送频率">
              {info.frequencyTimes}次 {info.frequencyDay}天
            </Descriptions.Item>
            <Descriptions.Item label="应答时长（秒）">{detail?.ackTimeout}</Descriptions.Item>
            <Descriptions.Item label="重发次数（次）">{detail?.maxRepeat}</Descriptions.Item>
            <Descriptions.Item label="驻留时长（天）">{info.lengthStay}</Descriptions.Item>
            {/* {detail?.channelCd === 5 && ( */}
            <Descriptions.Item label="短信签名">{detail?.smsSignName}</Descriptions.Item>
            {/* )} */}
            <Descriptions.Item label="有效期">
              {info.validityPeriod == 1
                ? '永久有效'
                : info?.expireTime
                ? `有效期至${info.expireTime}`
                : ''}
            </Descriptions.Item>
          </Descriptions>
          <div style={{ textAlign: 'center' }}>
            <Button
              size={'small'}
              onClick={() => {
                this.goback();
              }}
            >
              返回
            </Button>
          </div>
        </Card>
        {/* <PreviewModal
          visible={visible}
          contentData={contentData}
          type={type}
          changeVisible={() =>
            this.setState({ visible: false, contentData: undefined, type: undefined })
          }
        /> */}
        <Modal
          width="50%"
          title="预览"
          visible={visible}
          onCancel={() =>
            this.setState({ visible: false, contentData: undefined, type: undefined })
          }
          footer={[
            <Button
              key="back"
              type="primary"
              size="small"
              onClick={() =>
                this.setState({ visible: false, contentData: undefined, type: undefined })
              }
            >
              返回
            </Button>,
          ]}
        >
          <div dangerouslySetInnerHTML={{ __html: contentData }}></div>
        </Modal>
      </div>
    );
  }
}
export default connect(mapStateToProps)(MessageManagementDetail);
